<template>
	<div>
		<div class="leftContent d-flex">
			<el-scrollbar :max-height="maxHeight">
				<box class="mb-3" :wvalueth="480" :title="'数据管理'">
					<div class="mb-1">
						<p class="font-lan-gray-60">地图管理：</p>
						<el-row :gutter="16">
							<el-col :span="12">
								<coverage v-model="data.select" :placeholder="'图层管理'" :options="data.coverage" @change="slecetChange" />
							</el-col>
							<el-col :span="12">
								<maptype />
							</el-col>
						</el-row>
					</div>
					<div class="mb-1">
						<p class="font-lan-gray-60">气象管理：</p>
						<el-row :gutter="16">
							<el-col :span="12">
								<scSelect v-model="data.weather" :placeholder="'气象格点'" :options="data.weathers" @change="slecetChange" />
							</el-col>
							<el-col :span="12">
								<scSelect v-model="data.select" :placeholder="'种植作物'" :options="data.coverage" @change="slecetChange" />
							</el-col>
						</el-row>
					</div>
					<div>
						<p class="font-lan-gray-60">数据范围：</p>
						<scCascader v-model="data.cascader" :placeholder="'地址管理'" :options="storage.state.area" :label="'name'"
							:value="'id'" @change="acscaderChange" />
					</div>
          <!-- <div class="icons">
            <div class="iconInfo d-flex ai-center" >
              <div class="icon" style="background-color: rgba(81,209,232,0.6);border: 1px solid rgba(81,209,232,1);"></div>
              <div class="name">适宜：μ ＞ 0.8</div>
            </div>
            <div class="iconInfo d-flex ai-center" >
              <div class="icon" style="background-color: rgba(185,245,49,0.6);border: 1px solid rgba(185,245,49,1);"></div>
              <div class="mr-1">~</div>
              <div class="icon" style="background-color: rgba(49,245,134,0.6);border: 1px solid rgba(49,245,134,1);"></div>
              <div class="name">较适宜：0.5 ≤ μ ≤ 0.8</div>
            </div>
            <div class="iconInfo d-flex ai-center" >
              <div class="icon" style="background-color: rgba(245,153,49,0.6);border: 1px solid rgba(245,153,49,1);"></div>
              <div class="name">不适宜：μ ≤ 0.5</div>
            </div>
          </div> -->
				</box>
			</el-scrollbar>
      <div class="icons ml-3">
        <div v-for="(item, index) in data.farmlands" :key="index" class="iconInfo d-flex ai-center">
          <div class="icon" :style="{backgroundColor:item.background}"></div>
          <div class="name">{{ item.name }}</div>
        </div>
      </div>
		</div>
		<div class="rightContent">
			<el-scrollbar :max-height="maxHeight">
				<box :width="480" :title="'秋收适宜区统计'">
          <div class="d-flex ai-center mb-2">
            <div class="echart mr-3">
              <pieB :data="{
                title:'总面积',
                showTitle: true,
                color: data.farmlands.map((item) => item.background),
                list: data.farmlands
              }" />
            </div>
            <div class="flex-1">
              <div v-for="(item, index) in data.farmlands" :key="index" class="chartItem d-flex ai-center jc-between mb-2">
                <div>
                  <span class="chartIcon mr-2" :style="{ background: item.background }"></span>
                  <span class="font-lan">{{ item.name }}</span>
                </div>
                <div class="font-lan">
                  <span class="mr-3">{{ item.count }}亩</span>
                  <span class="ratio">{{ item.value }}%</span>
                </div>
              </div>
            </div>
          </div>
				</box>
			</el-scrollbar>
		</div>
    <daysBar :data="{dateList:data.dateList,forecast:data.forecast}" @timeChange="timeChange" @monthChange="monthChange"/>
	</div>
</template>
  
<script lang="ts">
import { defineComponent, ref, reactive, onMounted, onUnmounted, computed } from "vue";
import pieB from "@/chart/pieChart/pic-bole";
import daysBar from '@/components/timeBar/daysBar.vue'
import mapControler from "@/components/mapContainer/mapControler";
import {
  getXinZhiWeather,
  harvestIndication
} from "@/public/request/http";
import moment from "moment";
import storage from '@/store'
import {getSoilMoisture,getSoilTem,getSoilDepth,getRain,getSuitability} from "@/utils/springSowing"
import { calcMonthDate } from "@/utils/common";
import { ElMessage } from 'element-plus'
export default defineComponent({
	components: {
    pieB,
    daysBar
	},
	setup() {
		//变量
		// const maxHeight = ref(window.innerHeight-160+'px')
		const maxHeight = computed(() => window.innerHeight - 160 + 'px')
    const lngDiff = 0.031185
    const latDiff = 0.022595
		const data: any = reactive({
			coverage: [],
			select: null,
			cascader: [],
      weather:null,
      weathers:[{label: "气温",value:'0'},{label: "气压",value:'1'},{label: "风速",value:'2'},{label: "降水",value:'3'},{label: "土壤",value:'4'}],
      dataInfo: {},
      suitabilityIndexData: {
        xAxis: [],
        series: [],
      },
      appropriateStatisticsData: {
        count: 0,
        list: [],
      },
      suitableTrendData: {
        xAxis: [],
        series: [],
        unit: "",
      },
      IntervalDistributionData: {
        xAxis: [],
        series: [],
      },
      dateList: [],
      forecast:4,
      hint:0,
      date:moment().format('YYYY-MM-DD'),
      farmlands: [
        { name: '适宜', value: 0, background: '#93F5E1', des: '500亩以上', count: 0 },
        { name: '较适宜', value: 0, background: '#93AAF5', des: '200-500亩', count: 0 },
        { name: '不适宜', value: 0, background: '#93DBF5', des: '200亩以下', count: 0 }],
		});
		
		// 生命周期
		onMounted(async () => {
			mapControler.mapReSet();
			// getXinZhiWeatherData();
      // getHarvestIndication()
      let endDate = moment().add(data.forecast, "days").format("YYYY-MM-DD")>moment().endOf("month").format("YYYY-MM-DD")?moment().endOf("month").format("YYYY-MM-DD"):moment().add(data.forecast, "days").format("YYYY-MM-DD")
      data.dateList = calcMonthDate(moment().format('YYYY-MM'),false,endDate).map(item=>moment(item).format('DD'))
		});

		onUnmounted(() => {
			//
			mapControler.mapReSet();

		});

		//methods
    const getXinZhiWeatherData = async () => {
      try {
        //获取鄂托克前旗心知预报天气
        let res = await getXinZhiWeather({time:data.date})
        data.suitabilityIndexData={
          xAxis: [],
          series: [{data:[],type:'line',name:'预报',color:'#23D0C4'},{data:[],type:'dashed',name:'适宜'},{data:[],type:'dashed',name:'较适宜'}],
        }
        res.forEach(item => {
          data.suitabilityIndexData.xAxis.push(moment(item.date).format('MM-DD'))
          data.suitabilityIndexData.series[0].data.push(getSuitability(getSoilMoisture(item.avgSoilHum),getSoilTem(item.avgSoilTem),getSoilDepth(45),getRain(item.preAvg)).toFixed(2))
          data.suitabilityIndexData.series[1].data.push(0.8)
          data.suitabilityIndexData.series[2].data.push(0.5)
        });
      } catch (error) {}
    }

    const getHarvestIndication = async () =>{
      try {
        let res = await harvestIndication({url:`http://122.9.135.226:3060/projects/eqq/maize/${data.date}/`});
        mapControler.mapReSet();
        let total = 0
        let list = [{name:'适宜',value:0},{name:'较适宜',value:0},{name:'不适宜',value:0},]
        res.forEach(item => {
          item.suitability = item.index_harvest
          item.type = '适宜度'
          item.season = 'autumn'
          item.pointList = [];
          item.pointList.push({
            lng: parseFloat(item.lon) - lngDiff,
            lat: parseFloat(item.lat) + latDiff,
          });
          item.pointList.push({
            lng: parseFloat(item.lon) - lngDiff,
            lat: parseFloat(item.lat) - latDiff,
          });
          item.pointList.push({
            lng: parseFloat(item.lon) + lngDiff,
            lat: parseFloat(item.lat) - latDiff,
          });
          item.pointList.push({
            lng: parseFloat(item.lon) + lngDiff,
            lat: parseFloat(item.lat) + latDiff,
          });
          item.fillColor = getColorByValue(item.index_harv)
          item.fillOpacity = 0.6
          mapControler.drawArea(item);
          total += 9
          if(item.suitability == '适宜'){
            list[0].value += 9
          }else if(item.suitability == '较适宜'){
            list[1].value += 9
          }else{
            list[2].value += 9
          }
        });
        data.appropriateStatisticsData.count = total
        data.appropriateStatisticsData.list = list
      } catch (error) {
        ElMessage({
          message: '当前日期暂无数据',
          type: 'warning',
        })
      }
    }

    //根据适宜度获取颜色
    const getColorByValue = (val) => {
      let fillColor = '';
      if (val == '不适宜') {
        fillColor = "#F59931";
      }  else if (val == '较适宜') {
        fillColor = "#31f586";
      } else {
        fillColor = "#51d1e8";
      }
      return fillColor;
    };
    
    

		const timeChange = (val) => {
      //
      data.date = val
      getXinZhiWeatherData();
      getHarvestIndication()
    };

    const monthChange = async (val) =>{
      let endDate = moment().add(data.forecast, "days").format("YYYY-MM-DD")>moment(val).endOf("month").format("YYYY-MM-DD")?moment(val).endOf("month").format("YYYY-MM-DD"):moment().add(data.forecast, "days").format("YYYY-MM-DD")
      data.dateList = calcMonthDate(val, false, endDate).map(item => moment(item).format('DD'))
      let activeIndex = 0
      if(moment(val).format('YYYY-MM')<moment().format('YYYY-MM')){
        activeIndex = data.dateList.length - 1
      }else if(moment(val).format('YYYY-MM') == moment().format('YYYY-MM')){
        activeIndex = data.dateList.length - (1+parseInt(data.dateList[data.dateList.length - 1])-parseInt(moment().format('DD')))
      }else{
        activeIndex = 0
      }
      data.date = val+'-'+data.dateList[activeIndex]
      getXinZhiWeatherData();
      getHarvestIndication()
    }

		const slecetChange = (e) => {
			console.log(e);
		}

		const acscaderChange = (e) => {
			console.log(data.cascader);
		}

		// return
		return {
			data,
			slecetChange,
			acscaderChange,
			moment,
			maxHeight,
			storage,
      timeChange,
      monthChange,
		};
	},
});
</script>
  
<style lang="scss" scoped>
@import "@/assets/scss/index.scss";
.chartItem {
  padding: 4px 8px;
  background: rgba(153, 207, 255, 0.08);

  .chartIcon {
    display: inline-block;
    width: 12px;
    height: 12px;
    background: #93F5E1;
    border-radius: 2px 2px 2px 2px;
  }
}
</style>
  